package com.shut.vehicle.service.impl;

import com.github.pagehelper.PageHelper;
import com.shut.vehicle.dao.UserDao;
import com.shut.vehicle.interceptor.token.TokenCensor;
import com.shut.vehicle.pojo.User;
import com.shut.vehicle.service.UserService;
import com.shut.vehicle.wechat.WeChatLoginResult;
import com.shut.vehicle.wechat.WeChatUserManagement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 卢斌
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatUserManagement weChatUserManagement;

    @Autowired
    private TokenCensor tokenCensor;

    @Autowired
    private UserDao userDao;

    /**
     * 用户登录与注册；
     * - 存在用户信息则登录，数据库中如果没有该用户的openId则先完成基础的注册
     *
     * @param code 登录code
     * @return token
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String userLogin(String code) {
        // 调用微信小程序官方登录接口获取OpenId和SessionKey
        WeChatLoginResult loginResult = weChatUserManagement.requestLogin(code);
        // 根据用户的openId尝试获取用户实体信息
        User userEnt = userDao.getUserBaseInfoByOpenId(loginResult.getOpenId());
        // 如果无法拿到用户信息，说明用户是第一次登录则开始注册过程
        if (userEnt == null) {
            //注册一个新用户，仅包含最基本的信息（openId，默认的用户角色）
            userDao.saveUserBaseInfo(new User(loginResult.getOpenId()));
            userEnt = userDao.getUserBaseInfoByOpenId(loginResult.getOpenId());
        }
        Long currentTime = System.currentTimeMillis();
        userEnt.setLocalTime(currentTime);
        userDao.updateUserLoginTime(userEnt.getId(), currentTime);
        // 签发token，返回给用户
        return tokenCensor.tokenIssue(userEnt.getId(), loginResult.getSessionKey());
    }

    /**
     * 获取用户个人信息
     *
     * @param userId 用户ID
     * @return 用户信息
     */
    @Override
    public User getSelfInfo(Integer userId) {
        return userDao.getUserByUserId(userId);
    }

    @Override
    public List<User> getAllUsers(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return userDao.searchUser();
    }

}
